﻿using System;
using System.Web;
using System.IO;
using Core.Library;
using DataObject.Adv;
using DataObject.Image;
using DataObject.Product;

namespace WebApplication1.uploadify
{    
    public class Upload : IHttpHandler
    {
        private int _count;

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpPostedFile file = context.Request.Files["filedata"];

                var lstId = context.Request.QueryString["uId"];

                var arrayId     = lstId.Split('-');
                var userId      = ConvertUtility.ToInt32(arrayId[0]);
                var productId   = ConvertUtility.ToInt32(arrayId[1]);

                if (userId > 0)
                {
                    _count++;

                    var dt = DateTime.Now;

                    var fileExtension   = Path.GetExtension(file.FileName.ToLower());
                    var folderPath      = productId > 0 
                                            ? string.Format("/Data/UserData/{0}/{1}/{2}/{3}/{4}/", userId, dt.Year, dt.Month, dt.Day, productId) 
                                            : string.Format("/Data/UserData/{0}/{1}/{2}/{3}/", userId, dt.Year, dt.Month, dt.Day);

                    var folder = context.Server.MapPath(folderPath);

                    if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

                    var strPath = folderPath + file.FileName.ToLower();
                    var strFile = context.Server.MapPath(strPath);

                    file.SaveAs(strFile);                                   

                    var fileSize = file.ContentLength / 1000;
                    context.Response.Write(string.Format("{0},{1},{2}", strFile, file.FileName, fileSize));
                    context.Response.StatusCode = 200;

                    if (productId > 0)
                    {
                        try
                        {
                            var o = new ImageObject();
                            o.ProductId = productId;
                            o.Priority  = _count;
                            o.ImagePath = strPath;
                            ImageController.Image_Create(o);

                            if (_count == 1)
                                ProductController.Product_Update_ImagePath(productId, strPath);
                        }
                        catch { }
                    }                  

                    //------------------------------------------------------------------------------------------------------------------------------------------//
                    /*
                    var dt = DateTime.Now;

                    var encryptFileName = string.Format("{0}{1}{2}{3}{4}", dt.Year, dt.Month, dt.Day, dt.Minute, dt.Second);
                    var fileExtension   = Path.GetExtension(file.FileName.ToLower());

                    var fileName = string.Format("files/{0}/{1}/{2}/{3}/{4}", userId, dt.Year, dt.Month, dt.Day, encryptFileName + fileExtension);                    

                    var urlAction = SmallFile + "upload";

                    var parameters = new NameValueCollection { { "filename", fileName }, { "secret_key", SecretKey } };                    
                    var resp = (HttpWebResponse)HttpMethodHelper.PostFile(new Uri(urlAction), parameters, file.InputStream, fileName, GetMime(fileName), "filedata", null, null);

                    var result = false;
                    if (resp.StatusCode == HttpStatusCode.OK) result = true;
                    resp.Close();                    

                    var objSerial = new JavaScriptSerializer();
                    var json = objSerial.Serialize(result);
                    context.Response.Write(json);            
                    */
                    //------------------------------------------------------------------------------------------------------------------------------------------//
                }                
            }
            catch (Exception ex)
            {
                context.Response.Write("Uploadify Error: " + ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}